package com.tledu.spring05.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * user对象添加方法拦截器,给创建人和创建时间赋值
 *
 * @author Antg
 * @date 2021/8/9  19:11
 */
@Component
@Aspect
public class UserAspect {
    @Pointcut("execution(public * com.tledu.spring05.mapper..*.add(..))")
    public void method() {
    }

    @Before("method()")
    public void before(JoinPoint joinPoint) {
        System.out.println("用户添加切面");
        //获取参数列表
        Object[] args = joinPoint.getArgs();
        //遍历参数列表
        for (Object obj : args) {
            //使用反射获取对象的属性
            Class c = obj.getClass();
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if ("createBy".equals(field.getName())) {
                    try {
                        field.set(obj, "张三");//创建人
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                if ("createTime".equals(field.getName())) {
                    try {
                        field.set(obj, new Date());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
